import { userinfo } from '@/stores/counter';
import request from './useRequests';
import { ElMessage } from 'element-plus';

export default function subscribeCate() {
  async function getSubscribeStatus() {
    const user = userinfo();
    const id = user.baseInfo.id;
    const cate = user.pages.sub.cate;
    try {
      if (!user.baseInfo.id) {
        return false;
      }
      const res = await request({
        method: 'get',
        url: 'subscribe',
        params: {
          userId: id,
          categoryId: cate,
        },
      });

      if (res.data.status) {
        return res.data.data == 1;
      } else {
        return false;
      }
    } catch (e: any) {
      ElMessage({
        showClose: true,
        message: '获取订阅信息时发生未知错误',
        type: 'error',
      });
      return false;
    }
  }

  async function setSubscribeStatus(status: boolean) {
    const user = userinfo();
    const id = user.baseInfo.id;
    const cate = user.pages.sub.cate;
    try {
      const res = await request({
        method: 'put',
        url: 'subscribe',
        params: {
          userId: id,
          categoryId: cate,
          status: status,
        },
      });

      if (res.data.status) {
        if (res.data.data) {
          ElMessage({
            showClose: true,
            message: '订阅成功',
            type: 'success',
          });
        } else {
          ElMessage({
            showClose: true,
            message: '取消订阅成功',
            type: 'success',
          });
        }
        return true;
      } else {
        ElMessage({
          showClose: true,
          message: '更新失败',
          type: 'error',
        });
        return false;
      }
    } catch (e: any) {
      ElMessage({
        showClose: true,
        message: '更新订阅信息时发生未知错误',
        type: 'error',
      });
      return false;
    }
  }

  async function getSubscribeList() {
    const user = userinfo();
    const id = user.baseInfo.id;
    if (!id) {
      return;
    }
    try {
      const res = await request({
        method: 'get',
        url: 'subscribe/list',
        params: {
          userId: user.baseInfo.id,
        },
      });

      if (res.data.status) {
        user.subscribe = res.data.data;
      } else {
        ElMessage({
          showClose: true,
          message: '后台：获取订阅信息失败',
          type: 'error',
        });
      }
    } catch (e: any) {
      ElMessage({
        showClose: true,
        message: '前台：获取订阅信息失败',
        type: 'error',
      });
    }
  }
  return {
    getSubscribeStatus,
    setSubscribeStatus,
    getSubscribeList,
  };
}
